package com.dragon.sso.service;

import com.dragon.sso.ldap.LDAPConnector;
import com.dragon.sso.dto.LdapUserDetail;
import com.novell.ldap.LDAPException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author wangjg
 */
@Component
@Slf4j
public class LdapUserDetailService implements UserDetailsService {

    @Autowired
    private LDAPConnector ldapConnector;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LdapUserDetail userDetail = new LdapUserDetail();
        try {
            ldapConnector.searchOnePerson(username, ldapEntry -> {
                String mail = ldapEntry.getAttribute("mail").getStringValue();
                String displayName = ldapEntry.getAttribute("displayName").getStringValue();
                userDetail.setDn(ldapEntry.getDN());
                userDetail.setUsername(username);
                userDetail.setMail(mail);
                userDetail.setDisplayName(displayName);
            });
        } catch (LDAPException e) {
            log.error("login error", e);
            throw new UsernameNotFoundException("username not exist");
        } catch (Exception e) {
            log.error("login error", e);
            throw new UsernameNotFoundException("internal not exist");
        }
        return userDetail;
    }
}



